#!/usr/bin/php -q
<?php
     require "Services/Twilio.php";
     require "config.php";
     require_once "System/Daemon.php";


     $gmailAtomUrl="https://gmail.google.com/gmail/feed/atom";
     $gmailImapUrl = '{imap.gmail.com:993/imap/ssl}INBOX';

     $nl = "\r\n";

     // Allowed arguments & their defaults
     $runmode = array(
	  'daemon' => false,
	  'help' => false,
	  'write-initd' => false,
     );
     
     // Scan command line attributes for allowed arguments
     foreach ($argv as $k=>$arg) {
	  if (substr($arg, 0, 2) == '--' && isset($runmode[substr($arg, 2)])) {
	       $runmode[substr($arg, 2)] = true;
	  }
     }
    
     // Help mode. Shows allowed argumentents and quit directly
     if ($runmode['help'] == true) {
	  echo 'Usage: '.$argv[0].' [runmode]' . "\n";
	  echo 'Available runmodes:' . "\n";
	  foreach ($runmode as $runmod=>$val) {
	       echo ' --'.$runmod . "\n";
	  }
	  die();
     }

     // Setup
     $options = array(
	  'appName' => 'gmail2sms',
	  'appDir' => dirname(__FILE__),
	  'appDescription' => 'Sends gmail mail to Twilio sms',
	  'authorName' => 'Taras Lipatrov',
	  'authorEmail' => 'taras@lipatov.com',
	  'sysMaxExecutionTime' => '0',
	  'sysMaxInputTime' => '0',
	  //'sysMemoryLimit' => '1024M',
	  //'appRunAsGID' => 'nobody',
	  //'appRunAsUID' => 'nobody',
     );

     System_Daemon::setOptions($options);

     //System_Daemon::setOption("appName", "gmail2sms");  // Minimum configuration
     // This program can also be run in the background runmode --daemon
     if ($runmode['daemon']) {
	  // Spawn Daemon
	  echo "Here";
	  System_Daemon::start(); // Spawn Deamon!
     }

     // With the runmode --write-initd, this program can automatically write a
     // system startup file called: 'init.d'
     // This will make sure your daemon will be started on reboot
     if (!$runmode['write-initd']) {
	  System_Daemon::info('not writing an init.d script this time');
     } else {
	  if (($initd_location = System_Daemon::writeAutoRun()) === false) {
	       System_Daemon::notice('unable to write init.d script');
	  } else {
	       System_Daemon::info(
		    'sucessfully written startup script: %s',
		    $initd_location
	       );
	  }
     }

     function errorStop($error) {
	       System_Daemon::info($error);
	       System_Daemon::stop();
     }

     /* Function to check for new emails via gmail atom feed */
     function checkAtomLoop() {
	  /* Initialise cURL */
	  global $gmailAtomUrl,$gmailUser,$gmailPass,$nl,$inboxPoll;
	  $fullcount = "0";
	  
	  /* Watch the mailbox every second till we get a new msg */
	  while ($fullcount == "0") {
	       $c = curl_init($gmailAtomUrl);

	       $headers = array(
		    "Host: gmail.google.com",
		    "Authorization: Basic ".base64_encode($gmailUser.':'.$gmailPass),
		    "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4",
		    "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
		    "Accept-Language: en-gb,en;q=0.5",
		    "Accept-Encoding: text",
		    "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
		    "Date: ".date(DATE_RFC822)
	       );

	       curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
	       curl_setopt($c, CURLOPT_COOKIESESSION, true);
	       curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
	       curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
	       curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
	       curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
	       curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 1);
	       curl_setopt($c, CURLOPT_UNRESTRICTED_AUTH, 1);
	       curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 1);

	       $str = curl_exec($c) or errorStop('Cannot connect to Gmail: ' . imap_last_error());;
	       //echo $nl.$str.$nl;

	       $atomFeed = new SimpleXMLElement($str);
	       $kids = $atomFeed->children();
	       $fullcount = "{$kids->fullcount}";
	       /* Sleep if we didnt see new emails */
	       //echo $fullcount;
	       if ( $fullcount == "0") {
		    sleep($inboxPoll);
	       }
	       curl_close($c);
	  }
	  //echo "Found new email".$nl;
	  
	  /* return the number of new messages */
	  return($fullcount);
     }

     /* Function to fetch email via imap */
     function fetchMail(){
	  global $gmailImapUrl,$gmailUser,$gmailPass,$nl;

	  /* try to connect */
	  $inbox = imap_open($gmailImapUrl,$gmailUser,$gmailPass) 
	       or errorStop('Cannot connect to Gmail: ' . imap_last_error());

	  /* grab emails */
	  $emails = imap_search($inbox,'ALL');

	  /* if emails are returned, cycle through each... */
	  if($emails) {
	       /* begin output var */
	       $output = '';
	       
	       /* put the newest emails on top */
	       rsort($emails);
	       /* for every email... */
	       foreach($emails as $email_number) {
		    //$jobId='';
		    $jobId=rand(1000, 9999);
		    /* get information specific to this email */
		    $overview = imap_fetch_overview($inbox,$email_number,0);
		    $message = imap_fetchbody($inbox,$email_number,1);
		    $sms='';
		    $sms.='['.$jobId.'] ';
		    $sms.= $overview[0]->from.' / '.$overview[0]->subject.' / '.$message;
		    
		    if(strlen($sms) > 160)
			 $sms = substr($sms,0,155) . "...";

		    //System_Daemon::info($sms);

		    //echo $sms.$nl;
		    
		    sendSms($sms,$jobId);

		    /* Delete sent msg */
		    /* Depending on you gmail confirmation deleted emails will go to trash */
		    imap_delete($inbox,$email_number);
		    //System_Daemon::info('['.$jobId.'] Removed from Inbox');
	       }
	  } 
	  /* close the connection */
	  imap_close($inbox);
     }

     function sendSms($txt,$jobId) {
     	  global $twilioNumber,$smsRecipients,$twilioAccountSid,$twilioAuthToken,$nl;

	  try {
	       /* instantiate a new Twilio Rest Client */
	       $client = new Services_Twilio($twilioAccountSid, $twilioAuthToken);

	       /* for every SMS recepeint */
	       foreach ($smsRecipients as $number => $name) {
			 /* Send a new outgoing SMS */

		   // $sms = $client->account->sms_messages->create($twilioNumber,$number,$txt);
		    /* Log confirmation */
		    System_Daemon::info($txt);
		    System_Daemon::info('['.$jobId.'] Sent to: '.$name.' , '.$number);
	       }

	       /* close the object so we dont eatup all the mem */
	       unset($client); 
	  } catch(Exception $e) {
	       errorStop('Exception: ' .$e->getMessage());
	  }
     }

     /* main loop */
     while(true) {
	  $emailCount=checkAtomLoop();
	  //System_Daemon::info('['.$jobId.'] Found new messages');
	  fetchMail();
	  System_Daemon::iterate();
     }


?>